/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.modules.system.domain.Courseresourcesauditlog;
import me.zhengjie.modules.system.domain.Courseresourcescatalog;
import me.zhengjie.modules.system.domain.Teacher;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.mapper.CourseresourcesauditlogMapper;
import me.zhengjie.modules.system.mapper.TeacherMapper;
import me.zhengjie.modules.system.mapper.UserMapper;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.system.service.CourseresourcescatalogService;
import me.zhengjie.modules.system.domain.vo.CourseresourcescatalogQueryCriteria;
import me.zhengjie.modules.system.mapper.CourseresourcescatalogMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

/**
* @description 服务实现
* @author shitou
* @date 2024-12-12
**/
@Service
@RequiredArgsConstructor
public class CourseresourcescatalogServiceImpl extends ServiceImpl<CourseresourcescatalogMapper, Courseresourcescatalog> implements CourseresourcescatalogService {

    private final CourseresourcescatalogMapper courseresourcescatalogMapper;

    private final UserMapper userMapper;

    private final TeacherMapper teacherMapper;

    private final CourseresourcesauditlogMapper courseresourcesauditlogMapper;

    @Override
    public PageResult<Courseresourcescatalog> queryAll(CourseresourcescatalogQueryCriteria criteria, Page<Object> page){



        IPage<Courseresourcescatalog> courseresourcescatalogIPage = courseresourcescatalogMapper.findAll(criteria, page);
        List<Courseresourcescatalog> courseresourcescatalogList = courseresourcescatalogIPage.getRecords();

        List<Integer> resourcescatalogIds = new ArrayList<>();
        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
            resourcescatalogIds.add(courseresourcescatalog.getId());
        }
        List<Courseresourcesauditlog> courseresourcesauditlogList = new ArrayList<>();

        if(resourcescatalogIds.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseResourcesCatalogId",resourcescatalogIds);
            courseresourcesauditlogList = courseresourcesauditlogMapper.selectList(queryWrapper);
        }

        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){

            List<Courseresourcesauditlog> currentArr = new ArrayList<>();
            for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){
                if(courseresourcescatalog.getId() == courseresourcesauditlog.getCourseResourcesCatalogId()){
                    currentArr.add(courseresourcesauditlog);
                }
            }

            Collections.sort(currentArr, new Comparator<Courseresourcesauditlog>() {
                @Override
                public int compare(Courseresourcesauditlog o1, Courseresourcesauditlog o2) {
                    // 比较两个对象的 id 值
                    return o2.getId() - o1.getId();
                }
            });
            if(currentArr.size()!=0){
                if(currentArr.get(0).getState() == 3){
                    courseresourcescatalog.setRejectReason(currentArr.get(0).getContent());
                }
            }

        }
        courseresourcescatalogIPage.setRecords(courseresourcescatalogList);
        return PageUtil.toPage(courseresourcescatalogIPage);
    }

    public List<Courseresourcescatalog> queryOthenMsg(Integer id) {
        QueryWrapper<Courseresourcescatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).and(wrapper -> wrapper.eq("state", 3).or().eq("state", 2));

        return courseresourcescatalogMapper.selectList(queryWrapper);
    }

    public List<Courseresourcescatalog> queryOthenMsg2(Integer id) {
        QueryWrapper<Courseresourcescatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).and(wrapper -> wrapper.eq("state", 3).or().eq("state", 2).or().eq("state", 0));
        return courseresourcescatalogMapper.selectList(queryWrapper);
    }

    public List<Courseresourcescatalog> queryOthenMsg3(Integer id) {
        QueryWrapper<Courseresourcescatalog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).and(wrapper -> wrapper.ne("state", 1));
        return courseresourcescatalogMapper.selectList(queryWrapper);
    }


    public PageResult<Courseresourcescatalog> queryAuditCourseresourcescatalog(CourseresourcescatalogQueryCriteria criteria, Page<Object> page){
        List<Integer> list = new ArrayList<>();
//        list.add(1);
        list.add(2);
        criteria.setStateArr(list);
        IPage<Courseresourcescatalog> courseresourcescatalogIPage = courseresourcescatalogMapper.findAuditAll(criteria, page);
        List<Courseresourcescatalog> courseresourcescatalogList = courseresourcescatalogIPage.getRecords();

        List<Integer> resourcescatalogIds = new ArrayList<>();
        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){
            resourcescatalogIds.add(courseresourcescatalog.getId());
        }
        List<Courseresourcesauditlog> courseresourcesauditlogList = new ArrayList<>();

        if(resourcescatalogIds.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("courseResourcesCatalogId",resourcescatalogIds);
            courseresourcesauditlogList = courseresourcesauditlogMapper.selectList(queryWrapper);
        }

        for(Courseresourcescatalog courseresourcescatalog:courseresourcescatalogList){

            List<Courseresourcesauditlog> currentArr = new ArrayList<>();
            for(Courseresourcesauditlog courseresourcesauditlog:courseresourcesauditlogList){
                if(courseresourcescatalog.getId() == courseresourcesauditlog.getCourseResourcesCatalogId()){
                    currentArr.add(courseresourcesauditlog);
                }
            }

            Collections.sort(currentArr, new Comparator<Courseresourcesauditlog>() {
                @Override
                public int compare(Courseresourcesauditlog o1, Courseresourcesauditlog o2) {
                    // 比较两个对象的 id 值
                    return o2.getId() - o1.getId();
                }
            });
            if(currentArr.size()!=0){
                if(currentArr.get(0).getState() == 3){
                    courseresourcescatalog.setRejectReason(currentArr.get(0).getContent());
                }
            }

        }
        courseresourcescatalogIPage.setRecords(courseresourcescatalogList);

        return PageUtil.toPage(courseresourcescatalogIPage);
    }

    @Override
    public List<Courseresourcescatalog> queryAll(CourseresourcescatalogQueryCriteria criteria){
        return courseresourcescatalogMapper.findAll(criteria);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Courseresourcescatalog resources) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if(teacher!=null){
            resources.setTeacherId(Math.toIntExact(teacher.getId()));
        }

        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
        // 将 LocalDateTime 按照定义的格式进行格式化
        String formattedDateTime = now.format(formatter);

        resources.setCreateTime(formattedDateTime);
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Courseresourcescatalog resources) {
        Courseresourcescatalog courseresourcescatalog = getById(resources.getId());
        Integer status = 0;

        if(courseresourcescatalog.getState() != resources.getState()){

            status = 1;
        }
        courseresourcescatalog.copy(resources);
        if(status == 1){
            LocalDateTime now = LocalDateTime.now();
            // 定义日期时间格式化器，使用 yyyy-MMM-dd hh:mm:ss 格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss");
            // 将 LocalDateTime 按照定义的格式进行格式化
            String formattedDateTime = now.format(formatter);

            courseresourcescatalog.setCreateTime(formattedDateTime);
        }
        saveOrUpdate(courseresourcescatalog);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Courseresourcescatalog> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Courseresourcescatalog courseresourcescatalog : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" courseresourcesid",  courseresourcescatalog.getCourseresourcesId());
            map.put(" name",  courseresourcescatalog.getName());
            map.put(" teacherid",  courseresourcescatalog.getTeacherId());
            map.put(" state",  courseresourcescatalog.getState());
            map.put(" createtime",  courseresourcescatalog.getCreateTime());
            map.put(" lastupdatetime",  courseresourcescatalog.getLastupdatetime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}